package cn.jietuo.first.class01;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/27
 * @description:
 */
public class Code09_EvenTimesOddTimes {

    /**
     * 一个数组中有一种数出现了奇数次，其他数都出现了偶数次，怎么找到并打印这种数
     *
     * @param arr
     */
    public static void printOddTimesNum1(int[] arr) {
        if (arr == null || arr.length < 1) {
            return;
        }
        int eor = 0;
        for (int i = 0; i < arr.length; i++) {
            eor = eor ^ arr[i];
        }
        System.out.println("出现奇数次的数字是：" + eor);
    }

    /**
     * 一个数组中有两种数出现了奇数次，其他数都出现了偶数次，怎么找到并打印这两种数
     */
    public static void printOddTImesNum2(int[] arr) {
        if (arr == null || arr.length < 1) {
            return;
        }
        int eor = 0;
        for (int i = 0; i < arr.length; i++) {
            eor = eor ^ arr[i];
        }
        // 取出最右的1
        int rightOne = eor ^ (~eor | 1);
        int onlyOne = 0;
        for (int i = 0; i < arr.length; i++) {
            if ((rightOne & arr[i]) != 0) {
                onlyOne = onlyOne ^ arr[i];
            }
        }
        int otherOne = eor ^ onlyOne;
        System.out.println("这两个数字为：" + onlyOne + "," + otherOne);
    }


    public static void main(String[] args) {
        int[] arr1 = new int[]{2,3,5,8,1,3,5,2,8,3,3};
        printOddTimesNum1(arr1);
        int[] arr2 = new int[]{2,3,5,8,1,3,5,2,8,3,3,10};
        printOddTImesNum2(arr2);
    }

}
